package cn.migu.music.hangupsms.service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;

import cn.migu.music.hangupsms.cachemanage.LocalCacheManager;
import cn.migu.music.hangupsms.cachemanage.event.EventConstants;
import cn.migu.music.hangupsms.common.entity.*;
import cn.migu.music.hangupsms.repository.SmsProvinceSwitchSettingsMapper;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class SmsProvinceSwitchSettingsService implements SettingsApplyHandler {
    private static final String             TX_PREFIX = "smsProvinceSwitch";
    private static final String             OP_TABLE  = "t_migu_hangup_sms_province_switch";
    @Autowired
    private SmsProvinceSwitchSettingsMapper smsProvinceSwitchSettingsMapper;
    @Autowired
    private SettingsChangeLogService        changeLogService;
    @Autowired
    private LocalCacheManager               cacheManager;

    @PostConstruct
    public void init() {
        changeLogService.registerApply(TX_PREFIX, this);
    }

    /**
     * 修改省份设置
     * 
     * @param switchOperation
     * @return
     */
    @Transactional
    @PostMapping("/hangupsms/settings/sms-province-switch/edit/v1.0")
    public SettingResponse<String> updateSmsProvinceSettings(@RequestBody SmsProvinceSwitchOperation switchOperation) {
        SettingResponse<String> response = new SettingResponse<>();
        if (StringUtils.isEmpty(switchOperation.getProvinceId())) {
            response.setResultCode(SettingResponse.ERROR_CODE);
            response.setResultMessage("province id is empty");
            return response;
        }
        if (switchOperation.getSwitchOn() == null) {
            response.setResultCode(SettingResponse.ERROR_CODE);
            response.setResultMessage("switch is null");
            return response;
        }
        SmsProvinceSwitchSettings settingsOld = smsProvinceSwitchSettingsMapper.get(switchOperation.getProvinceId());
        if (settingsOld == null) {
            response.setResultCode(SettingResponse.ERROR_CODE);
            response.setResultMessage("no settings for province:" + switchOperation.getProvinceId());
            return response;
        }
        SmsProvinceSwitchSettings settings = new SmsProvinceSwitchSettings();
        settings.setProvinceId(switchOperation.getProvinceId());
        settings.setSwitchOn(switchOperation.getSwitchOn());
        settings.setChangeTime(LocalDateTime.now());
        settings.setApplyStatus(0);
        smsProvinceSwitchSettingsMapper.updateProvinceSwitch(settings.getProvinceId(), settings.getSwitchOn(), settings.getChangeTime());
        switchOperation.setOperationEnum(SettingOperationEnum.EDIT);
        changeLogService.addLog(switchOperation, OP_TABLE, settings.getProvinceId(), JSON.toJSONString(settings),
            JSON.toJSONString(settingsOld));
        response.setResultCode(SettingResponse.SUCCESS_CODE);
        response.setResultMessage(SettingResponse.SUCCESS_MSG);
        String txId = TX_PREFIX + "." + settings.getProvinceId();
        response.setData(txId);
        return response;
    }

    /**
     * 查询省份设置
     * 
     * @param provinceId
     *            省编码
     * @return
     */
    @GetMapping("/hangupsms/settings/sms-province-switch/display/v1.0")
    public SettingResponse<List<SmsProvinceSwitchSettings>> getSmsProvinceSwitch(@RequestParam String provinceId) {
        SettingResponse<List<SmsProvinceSwitchSettings>> response = new SettingResponse<>();
        if (StringUtils.isEmpty(provinceId)) {
            List<SmsProvinceSwitchSettings> settingsList = smsProvinceSwitchSettingsMapper.getAllSettings();
            response.setData(settingsList);
        } else {
            List<SmsProvinceSwitchSettings> settingsList = new ArrayList<>(1);
            SmsProvinceSwitchSettings settings = smsProvinceSwitchSettingsMapper.get(provinceId);
            if (settings != null) {
                settingsList.add(settings);
            }
            response.setData(settingsList);
        }
        response.setResultCode(SettingResponse.SUCCESS_CODE);
        return response;
    }

    @Override
    public boolean apply(String rowId, String user) {
        SmsProvinceSwitchSettings settings = smsProvinceSwitchSettingsMapper.getIgnoreDelete(rowId);
        if (settings != null) {
            smsProvinceSwitchSettingsMapper.updateApplyStatus(rowId, 1, LocalDateTime.now());
            SmsProvinceSwitchSettings updatedSettings = smsProvinceSwitchSettingsMapper.getIgnoreDelete(rowId);
            if (updatedSettings.getApplyStatus() != 1) {
                return false;
            }
            cacheManager.broadcastEvent(EventConstants.SMS_SEND_PROVINCE_CHANGED_EVENT);
            OperateBase operateBase = new OperateBase();
            operateBase.setOperationEnum(SettingOperationEnum.APPLY);
            operateBase.setOperateUser(user);
            changeLogService.addLog(operateBase, OP_TABLE, settings.getProvinceId(), JSON.toJSONString(updatedSettings), JSON.toJSONString(settings));
            return true;
        }
        return false;
    }
}
